package com.zoweunion.mechanic.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 转拼音工具
 */
public class PinyinUtil {
    private static final Pattern chinesePattern = Pattern.compile("[\u4e00-\u9fa5]");

    public static String convertToPinyin(char chinese) {
        //1.创建一个格式化输出对象
        HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
        //2.设置好格式
        outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        outputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        try {
            return PinyinHelper.toHanyuPinyinStringArray(chinese, outputFormat)[0];
        } catch (Exception e) {
            return String.valueOf(chinese);
        }
    }

    public static String convertToPinyinIc(char chinese) {
        return convertToPinyin(chinese).substring(0, 1);
    }

    /**
     * 汉子转首字母
     * @param chinese
     * @return
     */
    public static String convertToPinyinIc(String chinese) {
        StringBuilder stringBuffer = new StringBuilder();
        for (char c : chinese.toCharArray()) {
            stringBuffer.append(convertToPinyin(c), 0, 1);
        }
        return stringBuffer.toString();
    }

    public static boolean isHanyun(char item) {
        Matcher m = chinesePattern.matcher(String.valueOf(item));
        return m.find();
    }
}
